const express = require('express');
const router = express.Router();
const { Article } = require('../../models')
const { Op } = require('sequelize')
const { success, failure } = require('../../utils/responses');
const{NotFoundError}=require('../../utils/errors')

//查询文章列表
router.get('/', async function (req, res) {
    try {
        const query = req.query
        // 当前页数，如果不传值默认第一页
        const currentPage = Math.abs(Number(query.currentPage)) || 1
        // 每页显示的数量，如果不传值默认10
        const pageSize = Math.abs(Number(query.pageSize)) || 10
        //计算offset
        const offset = (currentPage - 1) * pageSize

        const condition = {
            order: [['id', 'DESC']],
            limit: pageSize,
            offset: offset
        }

        if (query.title) {
            condition.where = {
                title: {
                    [Op.like]: `%${query.title}%`
                }
            }
        }

        const { count, rows } = await Article.findAndCountAll(condition)
        success(res, '文章查询成功', {
            articles: rows,
            pagination: {
                total: count,
                currentPage,
                pageSize
            }
        })
    } catch (error) {
        failure(res, error)
    }

})
//查询文章详情
router.get('/:id', async function (req, res) {
    try {
        const article = await getArticle(req)
        success(res, '查询文章成功', { article })

    } catch (error) {
        failure(res, error)
    }

})

//创建文章
router.post('/', async function (req, res) {
    try {
        //创建白名单过滤
        const body = filterBody(req)
        const article = await Article.create(body);
        //200和201都表示成功,201表示创建新的资源
        success(res, '创建文章成功', { article }, 201)
    } catch (error) {
        failure(res, error)
    }
})

//删除文章
router.delete('/:id', async function (req, res) {
    try {
        const article = await getArticle(req)
        await article.destroy()
        success(res, '删除文章成功')
    } catch (error) {
        failure(res, error)
    }
})

//更新文章
router.put('/:id', async function (req, res) {
    try {
        const article = await getArticle(req)

        //创建白名单过滤
        const body = filterBody(req)

        //更新文章
        await article.update(body)
        success(res, '更新文章成功', { article })

    } catch (error) {
        failure(res, error)
    }
})

//查询当前文章：公共方法
async function getArticle(req) {
    //获取文章ID
    const { id } = req.params
    //查询当前文章ID
    const article = await Article.findByPk(id)

    //如果文章不存在，抛出错误异常
    if (!article) {
        throw new NotFoundError(`ID:${id}文章不存在`)
    }
    return article
}

// 白名单过滤：公共方法
function filterBody(req) {
    return {
        title: req.body.title,
        content: req.body.content,
    }
}
module.exports = router;